﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using EllenTang.Model;
namespace EllenTang.Dal
{
    public class BaseDal<T> where T : class,new()
    {
        DbContext Db = DbContextFactory.dbContext;
        /// <summary>
        /// 分页查询,并排序
        /// </summary>
        /// <typeparam name="s">限定的数据类型</typeparam>
        /// <param name="pageSize">每页多少行</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageCount">总页数</param>
        /// <param name="whereLamda">数据内容</param>
        /// <param name="orderbyLamda">排序主列</param>
        /// <param name="isAsc">排序方式</param>
        /// <returns></returns>
        public IQueryable<T> LoadEntities<s>(int pageSize, int pageIndex, out int pageCount, System.Linq.Expressions.Expression<Func<T, bool>> whereLamda, System.Linq.Expressions.Expression<Func<T, s>> orderbyLamda, bool isAsc)
        {
            IQueryable<T> temp = Db.Set<T>().Where<T>(whereLamda);
            pageCount = temp.Count();
            if (isAsc)
            {
                temp = temp.OrderBy<T, s>(orderbyLamda).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize);
            }
            else
            {
                temp = temp.OrderByDescending<T, s>(orderbyLamda).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize);
            }
            return temp;
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public bool DeleteEntities(T entities)
        {
            Db.Entry<T>(entities).State = EntityState.Deleted;
            return true;
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public T AddEntities(T entities)
        {
            
            Db.Set<T>().Add(entities);
            return entities;
        }


        /// <summary>
        /// 读取数据集
        /// </summary>
        /// <param name="whereLamda"></param>
        /// <returns></returns>
        public IQueryable<T> LoadEntities(System.Linq.Expressions.Expression<Func<T, bool>> whereLamda)
        {
            return Db.Set<T>().Where<T>(whereLamda);
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public bool UpdateEntities(T entities)
        {
            Db.Entry<T>(entities).State = EntityState.Modified;
            return true;
        }
    }
}
